//
//  RootViewController.m
//  test6
//
//  Created by Egor Zaderiy on 11/7/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "LabelViewController.h"
#import "EditAddViewController.h"

@implementation RootViewController

@synthesize names;
@synthesize images;
@synthesize doneButton , addViewController;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.names = [NSMutableArray arrayWithObjects: @"Egor" , @"Slava", @"Kirill", @"Sasha", @"Alex", nil];
    self.images =  [NSMutableArray arrayWithObjects: [[NSBundle mainBundle] 
                                               pathForResource:@"icon_item" ofType:@"gif"] , nil ];
    addViewController = [[EditAddViewController alloc] initWithNibName: @"EditAddViewController" bundle:nil];
    //-->> edit view
    // create button (done)
    UIBarButtonItem *dButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(didPressedDone)];
    self.doneButton = dButton;
    [dButton release];
    
    addViewController.navigationItem.rightBarButtonItem = doneButton;
    
    self.tableView.allowsSelectionDuringEditing = YES;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}


// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [names count ];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.

    cell.textLabel.text = [names objectAtIndex:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

/*
    //load image of cell
    NSString *imagefile = [[NSBundle mainBundle]
                           pathForResource:@"icon_item" ofType:@"gif"];
*/ //old setting image
    NSString *imagefile = [images objectAtIndex: 0];
    
    UIImage *uImage = [[UIImage alloc] initWithContentsOfFile: imagefile ];
    
    //set image for cell
    cell.imageView.image = uImage;
    
    return cell;
}


 // Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    
    [super setEditing:editing animated:animated];
	self.navigationItem.rightBarButtonItem.enabled = !editing;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Delete the row from the data source.
     //   [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade]; 
        [self.names removeObjectAtIndex: indexPath.row ];
       
        [tableView reloadData];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        NSLog(@"EDITING");
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (self.editing){
        
        addViewController.textName = [names objectAtIndex:indexPath.row];
        addViewController.editRow = indexPath.row;
        // Pass the selected object to the new view controller.
        
        [self.navigationController pushViewController:addViewController animated:YES];
    }
    else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
  	
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
	// called when the accessory view (disclosure button) is touched
    //создаем новый вью контроллер
    LabelViewController *detailViewController = [[LabelViewController alloc] initWithNibName: @"LabelViewController" bundle:nil];
    //что там будет написано
    detailViewController.textLabel1 = [names objectAtIndex:indexPath.row];
    
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    addViewController = nil;
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc
{
    [super dealloc];
}

//нажатие кнопочки Add
- (IBAction) didPressedAdd : (id) sender 
{
    //создаем новый вью контроллер
       //он уже создан
    //что там будет    
        //ничего
    addViewController.editRow = -1;
    [self.navigationController pushViewController:addViewController animated:YES];

}

- (void) didPressedDone
{
    NSString *text = addViewController.UITextName.text;

    if ( [text compare: @""] )  {
        
        if (addViewController.editRow < 0) {
            [self.names addObject: text];
            }
        else {
            [self.names replaceObjectAtIndex:addViewController.editRow withObject:text];
        }
        
        //addViewController.UITextName.text = @"";
        [self.navigationController popViewControllerAnimated: YES];
        
        if (addViewController.editRow > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:addViewController.editRow inSection:0];
            [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
            //[indexPath release];
        }
    }
    

}

- (IBAction) didPressedEdit : (id) sender 
{
    [self setEditing:!self.editing animated:YES];

}

@end


